package com.leesche.zcsp.node.app.v1.controller.param;

import com.leesche.zcsp.node.app.v1.controller.admin.AppAdminController;
import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.controller.web.v2.param.WebParamGroupController;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dennies yang on 2017-01-05.
 * APP端读取参数组，设备参数值  设置设备参数值
 *
 */
@Controller
@RequestMapping("/app/v1/param")
public class AppParamController  extends AppAdminController {
    private final static Logger LOGGER = LoggerFactory.getLogger(AppParamController.class);


    @Autowired
    PrivilegeService privilegeService;
    @Autowired
    PubDevSetParamService pubDevSetParamService;
    @Autowired
    PubDevConfigParamService pubDevConfigParamService;
    @Autowired
    PubParamGroupService pubParamGroupService;

    @Autowired
    LpubDevSetParamService lpubDevSetParamService;

    @Autowired
    NetService netService;
    @Autowired
    PubDeviceService pubDeviceService;



    /***
     * <p>通过设备类型ID 获取参数组</p>
     * @param devTypeId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "searchParamGroup", method = RequestMethod.POST)
    public Map<String,Object> searchParamGroup(Long devTypeId){
        try {
            QueryPubParamGroupCondition condition = new QueryPubParamGroupCondition();
            condition.setDevicetypeid(devTypeId);
            List<PubParamGroupDto> paramGroups = pubParamGroupService.findListsByCondition(condition);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("paramGroups", paramGroups);
            return WebResult.success().put("data",map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 通过参数组D获取参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "searchParam", method = RequestMethod.POST)
    public Map<String,Object> searchParam(Long paramGroupId,Long  deviceId){

        try {
            PubDevice device=getPubDevice(deviceId);//pubDeviceService.selectByPrimaryKey(pubDevSetParam.getDeviceid());
            if(device==null){
                return WebResult.failure("您没有权限操作此参数!").toMap();
            }
            QueryPubDevSetParamCondition condition=new QueryPubDevSetParamCondition();
            condition.setParamgroupid(paramGroupId);
            condition.setDeviceid(deviceId);
            List<PubDevSetParamDto> devParams = pubDevSetParamService.findListsByCondition(condition);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("devParams", devParams);
            return WebResult.success().put("data",map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    @ResponseBody
    @RequestMapping(value = "searchParamResult", method = RequestMethod.POST)
    public Map<String,Object> searchParamResult(Long devicieId,String source){

        try {
            PubDevice device=getPubDevice(devicieId);//pubDeviceService.selectByPrimaryKey(pubDevSetParam.getDeviceid());
            if(device==null){
                return WebResult.failure("您没有权限操作此参数!").toMap();
            }
            QueryPubDevSetParamCondition condition=new QueryPubDevSetParamCondition();
            condition.setDeviceid(devicieId);
            List<PubDevSetParamDto> devParams = pubDevSetParamService.findListsByCondition(condition);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("devParams", devParams);
            return WebResult.success().put("data",map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }
    @ResponseBody
    @RequestMapping(value = "searchParamLogResult", method = RequestMethod.POST)
    public Map<String,Object> searchParamLogResult(Long paramId,String source,String sdate){

        try {
            PubDevSetParam pubDevSetParam =pubDevSetParamService.selectByPrimaryKey(paramId);
            if(pubDevSetParam!=null) {
                PubDevice device = getPubDevice(pubDevSetParam.getDeviceid());//pubDeviceService.selectByPrimaryKey(pubDevSetParam.getDeviceid());
                if (device == null) {
                    return WebResult.failure("您没有权限操作此参数!").toMap();
                }
                QueryLpubDevSetParamCondition condition = new QueryLpubDevSetParamCondition();
                condition.setDevparamsetid(paramId);
                condition.setSource(source);
                condition.setSdate(sdate);
                List<LpubDevSetParamDto> devParams = lpubDevSetParamService.findListsByCondition(condition);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("devParams", devParams);
                return WebResult.success().put("data", map).toMap();
            }else{
                return WebResult.success().info("参数不存在!").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }
    @ResponseBody
    @RequestMapping(value = "searchParamByParamId", method = RequestMethod.POST)
    public Map<String,Object> searchParamByParamId(Long paramId){

        try {
            PubDevSetParam pubDevSetParam =pubDevSetParamService.selectByPrimaryKey(paramId);
            PubDevice device=getPubDevice(pubDevSetParam.getDeviceid());//pubDeviceService.selectByPrimaryKey(pubDevSetParam.getDeviceid());
            if(device!=null) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("devParam", pubDevSetParam);
                return WebResult.success().put("data", map).toMap();
            }else {
                return WebResult.failure("您没有权限查询此参数!").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /***
     *通过参数ID设置参数值
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "editParam", method = RequestMethod.POST)
    public Map<String,Object> editParam(Long paramId,Integer paramValue){
            PubDevSetParam pubDevSetParam =pubDevSetParamService.selectByPrimaryKey(paramId);
            if(pubDevSetParam!=null){
                pubDevSetParam.setDevparamvalue(paramValue);
                pubDevSetParam.setAdminid(privilegeService.getCurrentPrincipalForApp().getUserid());
                try{
                    //调用设置参数指令
                    PubDevice device=getPubDevice(pubDevSetParam.getDeviceid());//pubDeviceService.selectByPrimaryKey(pubDevSetParam.getDeviceid());
                    if(device!=null) {
                        if(paramValue<pubDevSetParam.getIndevparamval()||paramValue>pubDevSetParam.getOutdevparamval()){
                            return   WebResult.failure("请入"+pubDevSetParam.getIndevparamval()+"-"+pubDevSetParam.getOutdevparamval()+"的值!").toMap();
                        }
                        if(!netService.isOnline(device.getImme())){
                          return  WebResult.failure("设备:"+device.getImme()+"离线，请稍后重试").toMap();
                        }

                        netService.sendClientSetParam(device.getImme(),pubDevSetParam.getCommid(),paramValue);
                        pubDevSetParamService.updateByPrimaryKey(pubDevSetParam);
                        return WebResult.success().info("指令发送成功 等待设备响应!").toMap();
                    }else {
                        return WebResult.success().info("参数指令发送失败").toMap();
                    }
                }catch (Exception e){
                    LOGGER.error("exception",e);
                    return WebResult.failure(e).toMap();
                }
            }else{
                return WebResult.failure("您没有权限操作此参数!").toMap();
            }

    }


    /***
     *通过参数ID设置参数值
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getParam", method = RequestMethod.POST)
    public Map<String,Object> editParam(Long paramId){
        PubDevSetParam pubDevSetParam =pubDevSetParamService.selectByPrimaryKey(paramId);
        if(pubDevSetParam!=null){
            try{
                //调用设置参数指令
                PubDevice device=getPubDevice(pubDevSetParam.getDeviceid());//pubDeviceService.selectByPrimaryKey(pubDevSetParam.getDeviceid());
                if(device!=null) {
                    if(!netService.isOnline(device.getImme())){
                        return WebResult.failure("设备:"+device.getImme()+"离线，请稍后重试").toMap();
                    }
                    netService.sendClientGetParam(device.getImme(),pubDevSetParam.getCommid());
                    return WebResult.success().info("指令发送成功 等待设备响应!").toMap();
                }else {
                    return WebResult.failure("您没有权限操作此参数!").toMap();
                }
            }catch (Exception e){
                LOGGER.error("exception",e);
                return WebResult.failure(e).toMap();
            }
        }else{
            return WebResult.failure("该参数不存在").toMap();
        }

    }
    private PubDevice getPubDevice(
            Long deviceId
    ) {
        Long adminId = getAdminId();
        PubDevice device = pubDeviceService.selectByPrimaryKey(deviceId);
        if (device.getAdminid() != null) {
            if (!adminId.equals(device.getAdminid()) && device.getAdminid() != 0) {
                return null;
            } else if (adminId.equals(device.getAdminid())) {
                return device;
            }
        }
        return null;
    }


}
